package com.swak.algs;

/**
 * 等概率
 * 
 * @author lifeng
 */
public class Code05 {

	/**
	 * 等概率的出现 0 ~ 6
	 * 
	 * @return
	 */
	static int f1() {
		return (int) (Math.random() * 7);
	}

	/**
	 * 将f1 转换为等概率的 ：0 1
	 * 
	 * @return
	 */
	static int f1To01() {
		/*
		 * 0 1 2  -> 0
		 * 3  -> 重做
		 * 4 5 6  -> 1
		 */
		int ans = f1();
		while (ans == 3) {
			ans = f1();
		}
		return ans < 3 ? 0 : 1;
	}

	/**
	 * 通过f1 转换为等概率的 1 ~ 7 <br>
	 * 1~7 <br>
	 * 000 重做<br>
	 * 001 ~1<br>
	 * 111 ~7<br>
	 * 
	 * @return
	 */
	static int f1To1_7() {
		int ans = (f1To01() << 2) + (f1To01() << 1) + (f1To01() << 0);
		while (ans == 0) {
			ans = (f1To01() << 2) + (f1To01() << 1) + (f1To01() << 0);
		}
		return ans;
	}

	/**
	 * 非等概率的 0 和 1
	 * 
	 * @return
	 */
	static int f2() {
		return Math.random() < 0.84 ? 0 : 1;
	}

	/**
	 * 非等概率 转为 等概率的 0 1
	 * 
	 * @return
	 */
	static int f2To01() {
		/*
		 * 0	p
		 * 1	1-p
		 * 00	P*P
		 * 11	(1-p)*(1-p)
		 * 01	p*(1-p)
		 * 10	(1-p)*p
		 */
		int p1 = f2();
		do {
			p1 = f2();
		} while (p1 == f2());
		return p1;
	}

	public static void main(String[] args) {
		int times = 10000;
		int[] counts = new int[8];
		for (int i = 0; i < times; i++) {
			counts[f1To1_7()]++;
		}
		for (int i = 0; i < counts.length; i++) {
			System.out.println(i + " 执行了：" + counts[i] + " 次");
		}
		System.out.println("====================");
		counts = new int[8];
		for (int i = 0; i < times; i++) {
			counts[f2To01()]++;
		}
		for (int i = 0; i < counts.length; i++) {
			System.out.println(i + " 执行了：" + counts[i] + " 次");
		}
	}
}
